import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class CMain {

	public static void main(String[] p) {

		ArrayList<CMessage> list = new ArrayList<CMessage>();

		try {
			ServerSocket server = new ServerSocket(1022);
			System.out.println("Server is started.  IP:"
					+ Inet4Address.getLocalHost().getHostAddress());

			while (true) {
				// 等待客戶端，傳送訊息到伺服端
				Socket client = server.accept();
				System.out.println("Client is connected.");
				// 接收到遠端訊息後，傳訊息給客戶端
				DataInputStream streamIn = new DataInputStream(
						client.getInputStream());
				String strData = streamIn.readUTF();
				String[] strItems = strData.split("\t");
				// From \t To \t Message 利用\t分離訊息
				CMessage msg = new CMessage(strItems[0], strItems[1],
						strItems[2], false);

				for (CMessage m : list) {
					if (m.GetTo().equals(msg.GetFrom()) && !m.GetIsRead()) {
						m.SetIsRead(true);
						DataOutputStream streamOut = new DataOutputStream(
								client.getOutputStream());
						streamOut.writeUTF(m.GetMessage());
						streamOut.close();
						client.close();
						break;
					}
				}
				list.add(msg);
				client.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
